<template>
  <div>
    <div v-if="(getTreeMenuArr2.length == 1 && getTreeMenuArr2[0].children.length == 1) || getTreeMenuArr2.length == 0"
      class="goHome" @click="goindex">返回首页</div>
    <div class="newHeaderBox" v-else>
      <!-- <div class="cont">
  
        <div class="menuItem" @click.click="showChildrenMenu(item)" v-for="(item, index) in getTreeMenuArr"
          :key="index">
          <img src="../assets/image/newMenuItemIcon.png" class="icon" :class="item.route ? 'icon hide' : 'icon show'">
          <img src="../assets/image/newMenuItemIcon_hover.png" class="icon_hover"
            :class="item.route ? 'icon show' : 'icon_hover hide'">
          <p class="name">{{ item.name }}</p>
          <div class="children" v-show="item.route">
            <div class="childrenItem" v-for="(item2, index2) in item.children">{{ item2.name }}</div>
            <p class="close" @click="test(item)">+</p>
          </div>
        </div>
      </div> -->

      <el-menu :collapse="false" class="el-menu-demo width-1920" style="max-width: 1536px;" mode="horizontal" @select="handleSelect"
        background-color="#545c64" text-color="#fff" active-text-color="#ffd04b">
        <template v-if="getTreeMenuArr2.length" v-for="(item, index) in getTreeMenuArr2">
          <el-menu-item :index="objToStr(item)" :key="index" :class="item.isActived ? 'isActived' : ''"
            v-if="!item.children.length">
            <img src="../assets/image/newMenuItemIcon.png" class="icon">
            <img src="../assets/image/newMenuItemIcon_hover.png" class="icon_hover">
            <p class="name">{{ item.name }}</p>
          </el-menu-item>
          <el-submenu :index="objToStr(item)" :class="item.isActived ? 'isActived' : ''" :key="index" v-else>
            <template slot="title">
              <img src="../assets/image/newMenuItemIcon.png" class="icon">
              <img src="../assets/image/newMenuItemIcon_hover.png" class="icon_hover">
              <p class="name">{{ item.name }}</p>
            </template>
            <div v-if="item.children.length > 20" class="menu_20">
              <el-menu-item :index="objToStr(childrenItem)" v-for="(childrenItem, inx) in item.children" :key="inx">
                <span :class="childrenItem.isActived ? 'isActived' : ''">{{ childrenItem.name
                  }}</span>
              </el-menu-item>
            </div>
            <div v-if="item.children.length <= 20">
              <el-menu-item :index="objToStr(childrenItem)" v-for="(childrenItem, inx) in item.children" :key="inx">
                <span :class="childrenItem.isActived ? 'isActived' : ''">{{ childrenItem.name
                  }}</span>
              </el-menu-item>
            </div>
          </el-submenu>
        </template>
      </el-menu>
      <loginItem v-if="isShowLoginBtn" class="indexHeadUser"></loginItem>
    </div>
  </div>
</template>


<script>
import { mapGetters, mapMutations } from 'vuex'
import loginItem from './login-item'

export default {
  props: {
    isShowLoginBtn: {
      type: Boolean,
      default: true
    }
  },
  name: 'indexhead',
  components: { loginItem },
  data() {
    return {
      getTreeMenuArr2: []
    }
  },
  computed: {
    // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'getTreeMenuArr',
    ]),
  },
  //监听url中tablename的变化,改变后刷新页面
  watch: {
    '$route.query.tablename': {
      handler: function (val, oldVal) {
        if (val !== oldVal) {
          window.location.reload()
        }
      },
      deep: true
    }
  },
  methods: {
    ...mapMutations([
      'setBreadcrumb'
    ]),
    showChildrenMenu(item) {
      // this.getTreeMenuArr.forEach((element) => {
      //   element.route = false
      // })
      /**
       * tablename=area_province_month&
       * token=c53ddcc5-6cc1-439b-aba3-a8badf300b16&
       * menuType=130000&status=3&
       * breadcrumb=分省月度数据,分省月度数据&
       * headTag=河北省综合数据库
       */
      //childrenItem.tablename + '-' + childrenItem.name + '-' + childrenItem.url + '-' + childrenItem.icon + '-' + childrenItem.status
      console.log(item.children.length)
      if (item.children.length == 0) {
        const key = item.tablename + '-' + item.url + '-' + item.name
        this.handleSelect(item)
        // handleSelect()
      } else {
        item.route = !item.route
      }
    },
    getTreeMenuData(arr, parentId) {
      let resultArr = []
      for (var i = 0; i < arr.length; i++) {
        if (parentId == arr[i].parentid) {
          arr[i].children = this.getTreeMenuData(arr, arr[i].id)
          resultArr.push(arr[i])
          resultArr.sort((a, b) => {
            return Number(a.sortNo) - Number(b.sortNo)
          })
        }
      }
      return resultArr
    },
    // gohome() {
    //   this.$router.push({ path:'/home'})
    // },
    goindex() {
      // this.$router.push({ path: '/index' })
      const url = import.meta.env.VITE_PROXY_INDEX_URL
      window.location.href = url
    },
    objToStr(obj) {
      let str = ''
      for (let key in obj) {
        str += key + '=' + obj[key] + '&'
      }
      return str
    },
    strToObj(str) {
      let obj = {}
      let arr = str.split('&')
      arr.forEach((item) => {
        let key = item.split('=')[0]
        let value = item.split('=')[1]
        obj[key] = value
      })
      return obj
    },
    handleSelect(item, keyPath) {
      let token = localStorage.getItem('TOKEN_KEY')
      console.log(this.strToObj(item))
      console.log(this.strToObj(keyPath[0]))
      if (!token && key.indexOf == 'index-首页') {
        if (window.location.href.indexOf('login') <= 0) return this.$router.push('login')
        return
      }
      let url = this.strToObj(item).url
      let level1Name = this.strToObj(keyPath[0]).name || ''
      let level2Name = this.strToObj(item).name || ''
      let tablename = this.strToObj(item).tablename || ''
      let menuType = (this.strToObj(item).icon === null || this.strToObj(item).icon === 'null') ? localStorage.getItem('REGION_CODE') : this.strToObj(item).icon;
      let status = (this.strToObj(item).status === null || this.strToObj(item).status === 'null') ? localStorage.getItem('STATUS') : this.strToObj(item).status;
      // if (localStorage.getItem('STATUS') != 'undefined' && localStorage.getItem('STATUS') == 3) {
      //   menuType = localStorage.getItem('REGION_CODE')
      //   status = localStorage.getItem('STATUS')
      // }
      this.setBreadcrumb([level1Name, level2Name])
      if (token && (this.strToObj(keyPath[0]).url + this.strToObj(keyPath[0]).name) == 'index-首页') {
        if (import.meta.env.DEV) {
          window.location.replace("http://www.shujuquan.cn:3000/#/" + `${url}`);
        } else {
          window.location.replace("http://www.shujuquan.cn/#/" + `${url}`);
        }

      } else {
        console.log('item', this.strToObj(item).id)
        this.$router.push({ path: `/${url}`, query: { tablename: tablename, menuType: menuType, status: status, id: this.strToObj(item).id, ruleFlag: this.strToObj(item).ruleFlag } })
      }
    }
  },

  mounted() {
    // this.getTreeMenuArr = 
    // this.getTreeMenuArr = this.getTreeMenuData(this.getTreeMenuArr, -1)
    this.getTreeMenuArr2 = this.getTreeMenuArr
    console.log(this.getTreeMenuArr, 333)
    //使用this.$route.query.tablename去this.getTreeMenuArr中的tablename去匹，匹配到后，将该条数据增加isActived属性
    const id = this.$route.query.id;
    setTimeout(() => {
      if (id) {
        const setActived = (arr) => {
          arr.forEach(item => {
            this.$set(item, 'isActived', false);
            if (item.id === id) {
              this.$set(item, 'isActived', true);
            }
            if (item.children && item.children.length) {
              setActived(item.children);
              if (item.children.some(child => child.isActived)) {
                this.$set(item, 'isActived', true);
              }
            }
          });
        };
        setActived(this.getTreeMenuArr2);
      }
    }, 100);
    console.log(this.getTreeMenuArr2, 444)
    // if ($(".el-menu-demo>li").length <= 7) {
    //   $(".el-menu-demo").addClass("el-menu-short");
    //   $(".el-menu--collapse .el-menu .el-submenu, .el-menu--popup").css("width", "338px")
    // }
    // if ($(".el-menu-demo>li").length >= 8) {
    //   $(".el-submenu .el-submenu__title").css("width", "210px")
    // }
  }
}
</script>

<style lang="less" scoped>
.goHome {
  color: red;
  text-align: left;
  margin: 0 190px 10px;
  font-size: 16px;
  cursor: pointer;
  display: none;
}

.newHeaderBox {
  height: 50px;
  background: #948482;
  padding: 0 192px;

  .cont {
    padding: 0 30px;
    text-align: left;
    display: flex;
    align-items: center;
    height: 100%;

    .icon-a-lujing545 {
      font-size: 36px;
      margin-right: 52px;
      cursor: pointer;
    }

    //icon-a-lujing545 hover时，color变为#1D1819 -- #D82B2C从上到下渐变
    .icon-a-lujing545:hover {
      background: linear-gradient(180deg, #1D1819 0%, #D82B2C 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .menuItem {
      display: flex;
      align-items: center;
      color: #1D1819;
      cursor: pointer;
      position: relative;
      height: 100%;

      .children {
        position: absolute;
        left: 0;
        top: 50px;
        width: 200px;
        background: #948482;
        padding: 10px 20px;
        z-index: 999;
        line-height: 2;

        .close {
          position: absolute;
          right: 10px;
          top: 0;
          cursor: pointer;
          transform: rotate(45deg);
          font-size: 30px;
          line-height: 1;
        }

        .childrenItem:hover {
          font-weight: bold;
        }
      }

      .icon {
        display: block;
        margin-right: 8px;
        height: 28px;
      }

      .icon_hover {
        margin-right: 8px;
        height: 28px;
      }

      .name {
        font-size: 15px;
        font-weight: bold;
        margin-right: 13px;
      }

      .show {
        display: block;
      }

      .hide {
        display: none;
      }
    }

    .menuItem:hover {
      .icon {
        display: none;
      }

      .icon_hover {
        display: block;
      }
    }
  }

  :deep(.el-menu) {
    height: 100%;
    top: 0;
    left: 0;

    .el-submenu {
      height: 100%;

      .el-submenu__title {
        line-height: 50px;
        height: 50px;
        background: none !important;
        padding: 0;
        width: auto;
        font-size: 15px;
        font-weight: bold;
        color: #000 !important;
        display: flex;
        align-items: center;
        width: auto !important;

        .icon,
        .icon_hover {
          height: 28px;
          margin-right: 8px;
        }

        .icon_hover {
          display: none;
        }

        .name {
          margin-right: 13px;
        }

        .el-submenu__icon-arrow {
          display: none;
        }
      }
    }

    .el-menu-item {
      display: flex;
      background: none !important;
      align-items: center;
      color: #000 !important;
      font-weight: bold;
      height: 50px;
      line-height: 50px;
      padding: 0;
      width: auto !important;
      border: none !important;

      .icon,
      .icon_hover {
        height: 28px;
        margin-right: 8px;
      }

      .icon_hover {
        display: none;
      }

      .name {
        margin-right: 13px;
      }
    }

    .is-opened,
    .el-menu-item:hover {

      // .el-submenu__title{
      //   color: #D82B2C !important;
      // }
      .icon {
        display: none !important;
      }

      .icon_hover {
        display: block !important;
      }
    }

    .isActived {

      // .name{
      //   color: #D82B2C !important;
      // }
      .icon {
        display: none !important;
      }

      .icon_hover {
        display: block !important;
      }
    }
  }
}

.el-menu--horizontal {
  background: red;
}
</style>